import axios from "axios"
const instance = axios.create({
    baseURL: '',
    timeout: 10000,
})
let refreshing = false;
const queue = [];
instance.interceptors.request.use(function (config) {
    const accessToken = localStorage.getItem('access_token');
    if(accessToken) {
        config.headers.authorization = 'Bearer ' + accessToken;
    }
    return config;
})

instance.interceptors.response.use(
    (response) => {
        return response;
    },
    async (error) => {
        let { data, config } = error.response;
        if(refreshing) {
            return new Promise((resolve) => {
                queue.push({
                    config,
                    resolve
                });
            });
        }
        if (data.statusCode === 401 && !config.url.includes('/refresh')) {
            refreshing = true
            const res = await refreshToken();
            if(res.status === 200) {
                queue.forEach(({config, resolve}) => {
                    resolve(instance(config))
                })
                return instance(config);
            } else {
                alert(data || '登录过期，请重新登录');
            }
        } else {
            return error.response;
        }
    }
)

async function refreshToken() {
    const res = await instance.get('/refresh', {
        params: {
          token: localStorage.getItem('refresh_token')
        }
    });
    localStorage.setItem('access_token', res.data.accessToken);
    localStorage.setItem('refresh_token', res.data.refreshToken);
    return res;
}
export default instance
